<template>
<!-- 计划 -->
  <a-card :border='false'>
    <div>
      <!-- 查询 -->
      <my-table-screen
        :queryAdvanced="true"
        :queryParam="queryParam"
        :queryOptions="queryOptions"
        :queryData="queryData"
        @inputChange="inputChange"
        @handleFilter="handleFilter"
      ></my-table-screen>
      <div>
        <!-- table -->
        <my-table
          ref="mytable"
          :tableData="tableData"
          :tableLoading="tableLoading"
          @sortChange="sortChange"
          @switchChange="switchChange"
          @rowSelection="v=>rowSelection(v)"
          @tableHandleOut="tableHandleOut"
          @tableHandleIn="tableHandleIn"
        ></my-table>
        <!-- 分页 -->
        <pagination
          v-show="total>0"
          :total="total"
          :pageSizes="['10','20','50','80','100']"
          :page.sync="queryParam.page"
          :limit.sync="queryParam.page_size"
          @pagination="getList"
        />
      </div>
      <!-- 弹窗 -->
      <a-modal
        :title="visibleTitle"
        :confirm-loading="confirmLoading"
        :visible="visible"
        width="50%"
        :maskClosable="false"
        @ok="subimtData"
        @cancel="close"
      >
        <my-form
          ref="myform"
          :formData="formData"
          :formBox="formBox"
          :formOptions="formOptions"
          @subimt="subimt"
        ></my-form>
      </a-modal>
    </div>
  </a-card>
</template>

<script>
import { getAdList,getAdDetails,adSync } from "@/api/adv/ad";
import { getAccountListGet } from "@/api/adv/account";
import { setBudget,setBid } from "@/api/headlinesApi/index";
import { Status } from '@/api/statusInfo'

const addFormBox = {
  rules: {
    account_id: [{ required:true, message:'请选择至少一个账号',trigger:'change' }],
  },
  directions:'同步时间与数量相关,确认后将自动同步,请耐心等待',
  formItem:[
    { type:'select',prop:'account_id',label:'广告组账户',placeholder:"请选择广告组账户",options:'putAccount',
      isMultiple:'multiple'
    },
  ]
}
const budgetFormBox = {
  rules: {
    budget: [{ required:true, message:'请填写计划预算',trigger:'change' }],
  },
  directions:`
    1、24小时内修改不能超过20次
    2、单次修改预算幅度不能低于100元（增加或者减少）
    3、修改后预算金额，不能低于当前已消费金额的105%，以整百单位向上取整
  `,
  formItem:[ 
    { type:'inputNumber',prop:'budget',label:'计划预算',placeholder:"请填写计划预算" } 
  ]
}
const bidFormBox = {
  rules: {
    cpa_bid: [{ required:true, message:'请填写计划出价',trigger:'change' }],
  },
  directions:'批量修改数量不能超过100，修改的出价不能大于当前预算',
  formItem:[ 
    { type:'inputNumber',prop:'cpa_bid',label:'计划出价',placeholder:"请填写计划出价" } 
  ]
}

export default {
  data () {
    return {
      tableLoading:false,
      // 表格
      tableData:{
        rowKey:true,  //获取索引
        rowSelection:true,
        batchAction:[ 
          { title:'同步计划',item:'primary',tableFnc:'handleSyac',icon:'sync' },
          {
            title:'批量操作', item:'primary', type:'dropdown',
            children:[
              { name:'更改预算',tableFnc:'changeBudget' },
              { name:'更改出价',tableFnc:'changeBid' },
              { name:'计划开启',tableFnc:'handleEnable' },
              { name:'计划暂停',tableFnc:'handleDisable' },
            ],
          },
        ],
        tableDataSource:[],
        tableColumns:[
          { 
            dataIndex:'opt_status',align:'center',fixed:'left',width:120,scopedSlots: {customRender:'switch'},
            api:process.env.VUE_APP_ADV_OCEAN_API,postType:'ocean/ad',off:'AD_STATUS_DISABLE',run:'AD_STATUS_ENABLE',
          },
          { title:'计划名称',dataIndex:'name',align:'center',fixed:'left',width:300 },
          { title:'账户ID',dataIndex:'ocean_account',align:'center',width:300,scopedSlots: {customRender:'filter'},
            formatter: row => { return `${ row.ocean_account.name } ( ${ row.account_id } )` } 
          },
          { title:'预算（元）',align:'center',width:180,scopedSlots: {customRender:'filter'},
            formatter: row => { return `${ row.budget } ( ${ this.$cycle(row.budget_mode,this.$global.budgetMode) } )` } 
          },
          { title:'出价',dataIndex:'cpa_bid',align:'center',width:100,sorter:true },
          { title:'消耗',dataIndex:'cost',align:'center',width:100,sorter:true },
          { title:'计划状态',dataIndex:'status',align:'center',scopedSlots: {customRender:'filter'},
            formatter:(row)=>{
              for (const item of this.$global.adStatus) {
                if( item.value == row.status ) return item.label
              }
            },colorEvent:(row)=>{
              if(row.status == 'AD_STATUS_DELIVERY_OK'){ return `color:${ this.$global.colorStatus['green'] }` }
              else if(row.status == 'AD_STATUS_DISABLE'){ return `color:${ this.$global.colorStatus['orange'] }` }
              else if(row.status == 'AD_STATUS_AUDIT'){ return `color:${ this.$global.colorStatus['blue'] }` }
              else if(row.status == 'AD_STATUS_AUDIT_DENY'){ return `color:${ this.$global.colorStatus['red'] }` }
              else if(row.status == 'AD_STATUS_DELETE'){ return `color:${ this.$global.colorStatus['gray'] }` }
            },width:200
          },
          { title:'创建时间',dataIndex:'created_at',align:'center',width:180 },
          { title:'点击数',dataIndex:'click',align:'center',width:100 },
          { title:'展示数',dataIndex:'show',align:'center',width:100 },
          { title:'转化数',dataIndex:'convert',align:'center',width:100 },
          { title:'千次展示成本',dataIndex:'show_cost',align:'center',width:120 },
          { title:'点击成本',dataIndex:'click_cost',align:'center',width:100 },
          { title:'点击率',dataIndex:'click_rate',align:'center',width:100 },
          { title:'转化成本',dataIndex:'convert_cost',align:'center',width:100 },
          { title:'转化率',dataIndex:'convert_rate',align:'center',width:100 },
          {
            title: '操作',align:'center',fixed:'right',width:100,
            scopedSlots: {customRender: 'action'},
            tableBtn:[
              { title:'详情',type:'primary',btnType:'handleDetails' },
            ]
          },
        ]
      },
      // 查询
      queryParam:{  // 初始化数据
        status:'AD_STATUS_NOT_DELETE',
        task_id:'',
        page:1,
        page_size:10
      },
      total: 0,
      queryData:[
        { id:'status',title:'计划状态',type:'select',placeholder:'请选择计划状态',options:'adStatus' },
        { id:'account_id',title:'投放账户',type:'select',placeholder:'请选择投放账户',showSearch:true,options:'putAccount' },
        { id:'ad_create_time',title:'创建时间段',type:'times' },
        { id:'task_id',title:'批量计划ID',type:'input',placeholder:'按批量计划 ID 搜索' },
      ],
      queryOptions:{
        putAccount:[],
        adStatus:this.$global.adStatus,
      },
      // 弹窗
      formData:{},
      formBox:{},
      formOptions:{   //select数据
        putAccount:[],
      },
      visibleTitle:'',
      confirmLoading:false,
      visible:false,
      // 选项
      tabSelect:[]
    }
  },
  created () {
    this.getList()
    this.getAccount()
  },
  methods: {
    // 初始化数据
    async getList(){
      if( this.$route.query.task_id ) this.queryParam.task_id = this.$route.query.task_id  //获取批量任务ID
      this.tableLoading = true
      const res = await getAdList(this.queryParam)
      if( res.code === 'SUCCESS' ) this.tableData.tableDataSource = res.data.list,this.total = res.data.page_info.total
      this.tableLoading = false
    },
    // 投放账户
    async getAccount(){
      await getAccountListGet({ status:'ENABLE' }).then((res)=>{
        this.queryOptions.putAccount = this.$selectOptions(res.data,false,true,'account_id')
        this.formOptions.putAccount = this.$selectOptions(res.data,false,true,'account_id')
      })
    },
    // 表格头部按钮
    async tableHandleOut(tableFnc){
      this.formData = Object.assign({},{})
      // 新建广告组
      if( tableFnc === 'handleSyac'){
        this.formBox = addFormBox
        this.visibleTitle = '同步计划'
        this.visible = true
      }else if( this.tabSelect.length > 0 ){
        if( tableFnc === 'changeBudget' ){
          this.visibleTitle = '更改预算'
          this.formBox = budgetFormBox
          this.visible = true
        }else if ( tableFnc === 'changeBid' ){
          this.visibleTitle = '更改出价'
          this.formBox = bidFormBox
          this.visible = true
        }else {
          const $opt_status = new Status();
          let tableData = this.tableData.tableDataSource
          let batchDatas = {}
          let res = ''
          // 将数据遍历成  { 账号1:[ids],账号2:[ids], }
          this.tabSelect.forEach( idx => {
            if( !batchDatas.hasOwnProperty( tableData[idx].account_id ) ) batchDatas[tableData[idx].account_id] = [ ]
            batchDatas[tableData[idx].account_id].push(tableData[idx])
          });

          for (const key in batchDatas) {
            let obj = { advertiser_id:key, ad_ids:[],opt_status:'' }
            if( tableFnc === 'handleEnable' ) obj.opt_status = 'enable'   // 计划开启
            else if( tableFnc === 'handleDisable' ) obj.opt_status = 'disable'  // 计划暂停
              
            batchDatas[key].forEach(batchData => {
              obj.ad_ids.push( batchData.id )
            });

            res = await $opt_status.setStatus(obj.advertiser_id,obj)
            if( res.data.errors.length !== 0 ) this.$Tip( res.data.errors[0].error_message )
          }
          this.getList()
        } 
      } else return alert('请选择计划')
    },
    // 确认
    subimtData(){
      this.$refs.myform.submitForm()
    },
    // 确认提交
    async subimt(formData){
      let res
      if( this.visibleTitle === '同步计划' ){
        res = await adSync(formData.account_id)
      }else{
        let tableData = this.tableData.tableDataSource
        let batchDatas = {}
  
        this.tabSelect.forEach( idx => {
          if( !batchDatas.hasOwnProperty( tableData[idx].account_id ) ){
            batchDatas[tableData[idx].account_id] = [ ]
          }
          batchDatas[tableData[idx].account_id].push(tableData[idx])
        });
        for (const key in batchDatas) {
          let obj = { advertiser_id:key, data:[] }
          if( this.visibleTitle === '更改预算' ){
            batchDatas[key].forEach(batchData => {
              obj.data.push( { ad_id:batchData.id, budget:formData.budget } )
            });
            res = await setBudget(obj.advertiser_id,obj)
          }
          if( this.visibleTitle === '更改出价' ){
            batchDatas[key].forEach(batchData => {
              obj.data.push( { ad_id:batchData.id, bid:formData.cpa_bid } )
            });
            res = await setBid(obj.advertiser_id,obj)
          }
        }
      }
      this.$Tip(res)
      this.getList()
      this.visible = false
    },
    // 关闭弹窗
    close(){
      this.visible = false
    },
    // table表内列按钮
    async tableHandleIn(tableFnc,row){
      alert('功能未开启')
    },
    // 状态开启关闭
    switchChange(row) {
      const $opt_status = new Status();
      let quest = {
        advertiser_id:row.account_id,
        ad_ids:[row.id],
        opt_status:row.opt_status === 'AD_STATUS_ENABLE' ? 'disable' : 'enable'
      }
      $opt_status.setStatus(row.account_id,quest).then((res)=>{
        if( res.data.errors.length !== 0 ) this.$Tip( res.data.errors[0].error_message )
        else this.$Tip(res),this.getList()
      })
    },
    // query筛选input删除
    inputChange(){
      if( this.$route.query.task_id ) this.$router.push({ query: {} })  // 清空路由参数
    },
    // table选项
    rowSelection(con) {
      this.tabSelect = con
    },
    // 排序
    sortChange(sorter){
      const { field, order } = sorter
      this.queryParam.order_by = field
      this.queryParam.order_type = order === 'ascend' ? 'asc' : 'desc'
      this.handleFilter()
    },
    // 查询
    handleFilter(){
      this.queryParam.page = 1
      this.getList()
    },
  }
}
</script>
